<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Commit Description Generator</title>
  <script src="https://cdn.jsdelivr.net/npm/react@18.2.0/umd/react.production.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/react-dom@18.2.0/umd/react-dom.production.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/babel-standalone@6.26.0/babel.min.js"></script>
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    // Embedded md5.js logic for Baidu Translate API signature
    var MD5 = function (string) {function RotateLeft(lValue,iShiftBits){return(lValue<<iShiftBits)|(lValue>>>(32-iShiftBits));}function AddUnsigned(lX,lY){var lX4,lY4,lX8,lY8,lResult;lX8=(lX&0x80000000);lY8=(lY&0x80000000);lX4=(lX&0x40000000);lY4=(lY&0x40000000);lResult=(lX&0x3FFFFFFF)+(lY&0x3FFFFFFF);if(lX4&lY4){return(lResult^0x80000000^lX8^lY8);}if(lX4|lY4){if(lResult&0x40000000){return(lResult^0xC0000000^lX8^lY8);}else{return(lResult^0x40000000^lX8^lY8);}}else{return(lResult^lX8^lY8);}}function F(x,y,z){return(x&y)|((~x)&z);}function G(x,y,z){return(x&z)|(y&(~z));}function H(x,y,z){return(x^y^z);}function I(x,y,z){return(y^(x|(~z)));}function FF(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(F(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b);};function GG(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(G(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b);};function HH(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(H(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b);};function II(a,b,c,d,x,s,ac){a=AddUnsigned(a,AddUnsigned(AddUnsigned(I(b,c,d),x),ac));return AddUnsigned(RotateLeft(a,s),b);};function ConvertToWordArray(string){var lWordCount;var lMessageLength=string.length;var lNumberOfWords_temp1=lMessageLength+8;var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1%64))/64;var lNumberOfWords=(lNumberOfWords_temp2+1)*16;var lWordArray=Array(lNumberOfWords-1);var lBytePosition=0;var lByteCount=0;while(lByteCount<lMessageLength){lWordCount=(lByteCount-(lByteCount%4))/4;lBytePosition=(lByteCount%4)*8;lWordArray[lWordCount]=(lWordArray[lWordCount]|(string.charCodeAt(lByteCount)<<lBytePosition));lByteCount++;}lWordCount=(lByteCount-(lByteCount%4))/4;lBytePosition=(lByteCount%4)*8;lWordArray[lWordCount]=lWordArray[lWordCount]|(0x80<<lBytePosition);lWordArray[lNumberOfWords-2]=lMessageLength<<3;lWordArray[lNumberOfWords-1]=lMessageLength>>>29;return lWordArray;};function WordToHex(lValue){var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;for(lCount=0;lCount<=3;lCount++){lByte=(lValue>>>(lCount*8))&255;WordToHexValue_temp="0"+lByte.toString(16);WordToHexValue=WordToHexValue+WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);}return WordToHexValue;};function Utf8Encode(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}return utftext;};var x=Array();var k,AA,BB,CC,DD,a,b,c,d;var S11=7,S12=12,S13=17,S14=22;var S21=5,S22=9,S23=14,S24=20;var S31=4,S32=11,S33=16,S34=23;var S41=6,S42=10,S43=15,S44=21;string=Utf8Encode(string);x=ConvertToWordArray(string);a=0x67452301;b=0xEFCDAB89;c=0x98BADCFE;d=0x10325476;for(k=0;k<x.length;k+=16){AA=a;BB=b;CC=c;DD=d;a=FF(a,b,c,d,x[k+0],S11,0xD76AA478);d=FF(d,a,b,c,x[k+1],S12,0xE8C7B756);c=FF(c,d,a,b,x[k+2],S13,0x242070DB);b=FF(b,c,d,a,x[k+3],S14,0xC1BDCEEE);a=FF(a,b,c,d,x[k+4],S11,0xF57C0FAF);d=FF(d,a,b,c,x[k+5],S12,0x4787C62A);c=FF(c,d,a,b,x[k+6],S13,0xA8304613);b=FF(b,c,d,a,x[k+7],S14,0xFD469501);a=FF(a,b,c,d,x[k+8],S11,0x698098D8);d=FF(d,a,b,c,x[k+9],S12,0x8B44F7AF);c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);a=FF(a,b,c,d,x[k+12],S11,0x6B901122);d=FF(d,a,b,c,x[k+13],S12,0xFD987193);c=FF(c,d,a,b,x[k+14],S13,0xA679438E);b=FF(b,c,d,a,x[k+15],S14,0x49B40821);a=GG(a,b,c,d,x[k+1],S21,0xF61E2562);d=GG(d,a,b,c,x[k+6],S22,0xC040B340);c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);b=GG(b,c,d,a,x[k+0],S24,0xE9B6C7AA);a=GG(a,b,c,d,x[k+5],S21,0xD62F105D);d=GG(d,a,b,c,x[k+10],S22,0x2441453);c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);b=GG(b,c,d,a,x[k+4],S24,0xE7D3FBC8);a=GG(a,b,c,d,x[k+9],S21,0x21E1CDE6);d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);c=GG(c,d,a,b,x[k+3],S23,0xF4D50D87);b=GG(b,c,d,a,x[k+8],S24,0x455A14ED);a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);d=GG(d,a,b,c,x[k+2],S22,0xFCEFA3F8);c=GG(c,d,a,b,x[k+7],S23,0x676F02D9);b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);a=HH(a,b,c,d,x[k+5],S31,0xFFFA3942);d=HH(d,a,b,c,x[k+8],S32,0x8771F681);c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);a=HH(a,b,c,d,x[k+1],S31,0xA4BEEA44);d=HH(d,a,b,c,x[k+4],S32,0x4BDECFA9);c=HH(c,d,a,b,x[k+7],S33,0xF6BB4B60);b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);d=HH(d,a,b,c,x[k+0],S32,0xEAA127FA);c=HH(c,d,a,b,x[k+3],S33,0xD4EF3085);b=HH(b,c,d,a,x[k+6],S34,0x4881D05);a=HH(a,b,c,d,x[k+9],S31,0xD9D4D039);d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);b=HH(b,c,d,a,x[k+2],S34,0xC4AC5665);a=II(a,b,c,d,x[k+0],S41,0xF4292244);d=II(d,a,b,c,x[k+7],S42,0x432AFF97);c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);b=II(b,c,d,a,x[k+5],S44,0xFC93A039);a=II(a,b,c,d,x[k+12],S41,0x655B59C3);d=II(d,a,b,c,x[k+3],S42,0x8F0CCC92);c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);b=II(b,c,d,a,x[k+1],S44,0x85845DD1);a=II(a,b,c,d,x[k+8],S41,0x6FA87E4F);d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);c=II(c,d,a,b,x[k+6],S43,0xA3014314);b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);a=II(a,b,c,d,x[k+4],S41,0xF7537E82);d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);c=II(c,d,a,b,x[k+2],S43,0x2AD7D2BB);b=II(b,c,d,a,x[k+9],S44,0xEB86D391);a=AddUnsigned(a,AA);b=AddUnsigned(b,BB);c=AddUnsigned(c,CC);d=AddUnsigned(d,DD);}var temp=WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);return temp.toLowerCase();}
  </script>
</head>

<body>
  <div id="root"></div>
  <script type="text/babel">
    const { useState, useEffect } = React;

    const CommitForm = () => {
      const [formData, setFormData] = useState({
        commit_path_info: '',
        emailPrefix: '',
        emailString: '',
        changeDescription: '',
        integrate_from_flag: 'N',
        integrate_from_id: '',
        changeCategory: '新增需求',
        rootCause: '',
        solution: '',
        jiraID_flag: 'N',
        jiraID: '',
        cveID_flag: 'N',
        cveID: '',
        affectedFunction: [],
        applicableProject: '分支测试',
        projectname: '',
        projectType: '标准项目',
        riskLevel: `质量风险-问题遇到的概率大小: 
质量风险-出现问题后的可恢复性: 
质量风险-前后版本的兼容一致性: 
质量风险-问题对客户业务场景的影响: `,
        relatedChanges_flag: 'N',
        relatedChanges: '',
        atcDoc_flag: 'N',
        atcDoc: '',
        dmProtocol: 'N',
        thirdPartyServer: 'N',
        thirdPartySoftware: 'N',
        audioDefault: 'N',
        configChange: 'N',
        mbnChange: 'N',
        timerIssue: 'N',
        paramCompatibility: 'N',
        storageWear: 'N',
        sensitiveInfo: 'N',
        paramReset: 'N',
        apiDocUpdate: 'N',
        otherBranches: 'N',
        otherBranchesText: '',
        rnDescription: 'N',
        rnDescriptionText: '',
        fsgUpdate: 'N',
        fsgTag: '',
        fsgSW: '',
        fsgRF: '',
        fsgDate: '',
        softwareTest: 'N',
        softwareTestText: '',
        stressTest: 'N',
        stressTestText: '',
        hardwareTest: 'N',
        hardwareTestText: '',
        apAtCommand: 'N'
      });
      
      const [outputText, setOutputText] = useState('');

      const generateOutput = () => {
        let output = `${formData.commit_path_info}<${formData.emailPrefix}><${formData.emailString}>: `;
        if (formData.integrate_from_flag === 'Y') {
          output += `[integrate from ${formData.integrate_from_id}] ${formData.changeDescription}\n`;
        }
        else {
          output += `${formData.changeDescription}\n`;
        } 
        output += `<修改分类>: ${formData.changeCategory}\n`;
        output += `<根本原因>: ${formData.rootCause}\n`;
        output += `<解决方案>: ${formData.solution}\n`;
        output += `[Jira ID]: ${formData.jiraID_flag}${formData.jiraID_flag === 'Y' ? `, ${formData.jiraID}` : ''}\n`;
        output += `[CVE ID]: ${formData.cveID_flag}${formData.cveID_flag === 'Y' ? `, ${formData.cveID}` : ''}\n`;
        output += `<影响功能名称>: ${formData.affectedFunction.length > 0 ? formData.affectedFunction.join(',') : 'N'}\n`;
        output += `<适用项目>: ${formData.applicableProject === "其他" ? `${formData.projectname}` : `${formData.applicableProject}`} \n`;
        output += `<影响项目类型>: ${formData.projectType}\n`;
        output += `<风险等级>: ${formData.riskLevel}\n`;
        output += `[关联其它修改点]: ${formData.relatedChanges_flag}${formData.relatedChanges_flag === 'Y' ? `, ${formData.relatedChanges}` : ''}\n`;
        output += `\n<<<研发自检>>>\n`;
        output += `[ATC 文档名称]: ${formData.atcDoc_flag}${formData.atcDoc_flag === 'Y' ? `, ${formData.atcDoc}` : ''}\n`;
        output += `<是否使用运营商DM协议:Onenet/OMA/LwM2M等>: ${formData.dmProtocol}\n`;
        output += `<是否使用第三方服务器:XTRA等>: ${formData.thirdPartyServer}\n`;
        output += `<是否使用第三方软件:SSL库等>: ${formData.thirdPartySoftware}\n`;
        output += `<是否为音频默认参数>: ${formData.audioDefault}\n`;
        output += `<是否修改配置文件:rawdata分区数据修改等>: ${formData.configChange}\n`;
        output += `<是否修改MBN>: ${formData.mbnChange}\n`;
        output += `<是否存在定时器非预期的唤醒和休眠锁未释放>: ${formData.timerIssue}\n`;
        output += `<是否存在参数结构变更影响前后版本的兼容性>: ${formData.paramCompatibility}\n`;
        output += `<是否存在NV/文件系统/存储介质的频繁擦写>: ${formData.storageWear}\n`;
        output += `<是否存在客户敏感信息泄漏>: ${formData.sensitiveInfo}\n`;
        output += `<是否存在重要参数还原失败系统不停重启或变砖>: ${formData.paramReset}\n`;
        output += `<是否更新API文档>: ${formData.apiDocUpdate}\n`;
        output += `[其他需要合入的分支]: ${formData.otherBranches}${formData.otherBranches === 'Y' ? `, ${formData.otherBranchesText}` : ''}\n`;
        output += `[RN描述]: ${formData.rnDescription}${formData.rnDescription === 'Y' ? `, ${formData.rnDescriptionText}` : ''}\n`;
        output += `<FSG/NV更新>: ${formData.fsgUpdate}\n`;
        if (formData.fsgUpdate === 'Y') {
          output += `<FSG TAG>: ${formData.fsgTag}\n`;
          output += `<FSG SW>: ${formData.fsgSW}\n`;
          output += `<FSG RF>: ${formData.fsgRF}\n`;
          output += `<FSG DATE>: ${formData.fsgDate}\n`;
        }
        output += `\n<<< Test Notes >>>\n`;
        output += `<软件测试>: ${formData.softwareTest}${formData.softwareTestText ? `, ${formData.softwareTestText}` : ''}\n`;
        output += `<压力测试>: ${formData.stressTest}${formData.stressTestText ? `, ${formData.stressTestText}` : ''}\n`;
        output += `<硬件测试>: ${formData.hardwareTest}${formData.hardwareTestText ? `, ${formData.hardwareTestText}` : ''}\n`;
        output += `<AP侧AT指令新增或修改>: ${formData.apAtCommand}\n`;
        return output;
      };
      
      {/*English block*/}
      const [formData_English, setFormData_English] = useState({
        commit_path_info: '',
        emailPrefix: '',
        emailString: '',
        changeDescription: '',
        integrate_from_flag: 'N',
        integrate_from_id: '',
        changeCategory: 'new requirements',
        rootCause: '',
        solution: '',
        jiraID_flag: 'N',
        jiraID: '',
        cveID_flag: 'N',
        cveID: '',
        affectedFunction: [],
        applicableProject: 'branch test',
        projectname : '',
        projectType:'Standard project',
        riskLevel: `Quality Risk-Likelihood of Issue Occurrence: 
Quality Risk-Recoverability if Issue Occurs: 
Quality Risk-Backward Compatibility Across Versions: 
Quality Risk-Impact on Customer Use Cases: `,
        relatedChanges_flag: 'N',
        relatedChanges: '',
        atcDoc_flag: 'N',
        atcDoc: '',
        dmProtocol: 'N',
        thirdPartyServer: 'N',
        thirdPartySoftware: 'N',
        audioDefault: 'N',
        configChange: 'N',
        mbnChange: 'N',
        timerIssue: 'N',
        paramCompatibility: 'N',
        storageWear: 'N',
        sensitiveInfo: 'N',
        paramReset: 'N',
        apiDocUpdate: 'N',
        otherBranches: 'N',
        otherBranchesText: '',
        rnDescription: 'N',
        rnDescriptionText: '',
        fsgUpdate: 'N',
        fsgTag: '',
        fsgSW: '',
        fsgRF: '',
        fsgDate: '',
        softwareTest: 'N',
        softwareTestText: '',
        stressTest: 'N',
        stressTestText: '',
        hardwareTest: 'N',
        hardwareTestText: '',
        apAtCommand: 'N'
      });
      
      const [outputText_English, setOutputText_English] = useState('');

      const generateOutput_English = () => {
        let output = `${formData_English.commit_path_info}<${formData_English.emailPrefix}><${formData_English.emailString}>: `;
        if (formData_English.integrate_from_flag === 'Y') {
          output += `[integrate from ${formData_English.integrate_from_id}] ${formData_English.changeDescription}\n`;
        }
        else {
          output += `${formData_English.changeDescription}\n`;
        }
        output += `<Change Type>: ${formData_English.changeCategory}\n`;
        output += `<Root Cause>: ${formData_English.rootCause}\n`;
        output += `<Solution>: ${formData_English.solution}\n`;
        output += `[Jira ID]: ${formData_English.jiraID_flag}${formData_English.jiraID_flag === 'Y' ? `, ${formData_English.jiraID}` : ''}\n`;
        output += `[CVE ID]: ${formData_English.cveID_flag}${formData_English.cveID_flag === 'Y' ? `, ${formData_English.cveID}` : ''}\n`;
        output += `<Affected Function Name>: ${formData_English.affectedFunction.length > 0 ? formData_English.affectedFunction.join(',') : 'N'}\n`;
        output += `<Applicable Project>: ${formData_English.applicableProject === "others" ? `${formData_English.projectname}` : `${formData_English.applicableProject}`} \n`;
        output += `<Affected Project Type>: ${formData_English.projectType}\n`;
        output += `<Risk Llvel>: ${formData_English.riskLevel}\n`;
        output += `[Associated Changes]: ${formData_English.relatedChanges_flag}${formData_English.relatedChanges_flag === 'Y' ? `, ${formData_English.relatedChanges}` : ''}\n`;
        output += `\n<<<Self-check by Developers>>>\n`;
        output += `[ATC Document Name]: ${formData_English.atcDoc_flag}${formData_English.atcDoc_flag === 'Y' ? `, ${formData_English.atcDoc}` : ''}\n`;
        output += `<Operator DM protocol: such as Onenet/OMA/LwM2M>: ${formData_English.dmProtocol}\n`;
        output += `<Server of Third-Party: such as XTRA>: ${formData_English.thirdPartyServer}\n`;
        output += `<SW of Third-Party: such as SSL>: ${formData_English.thirdPartySoftware}\n`;
        output += `<Audio Default Parameters>: ${formData_English.audioDefault}\n`;
        output += `<Conf files Modification: such as rawdata Partition>: ${formData_English.configChange}\n`;
        output += `<MBN Modifications>: ${formData_English.mbnChange}\n`
        output += `<Whether the timer has an unexpected wake up and sleep lock that is not released>: ${formData_English.timerIssue}\n`;
        output += `<Check whether the parameter structure changes affect the compatibility between versions before and after>: ${formData_English.paramCompatibility}\n`;
        output += `<Frequent Erasing of NV/File System/Storage Media>: ${formData_English.storageWear}\n`;
        output += `<Whether there is leakage of customer sensitive information>: ${formData_English.sensitiveInfo}\n`;
        output += `<Check whether important parameters fail to be restored. The system keeps restarting or becomes brick>: ${formData_English.paramReset}\n`;
        output += `<Whether API document is updated>: ${formData_English.apiDocUpdate}\n`;
        output += `[Other Branches to be Merged]: ${formData_English.otherBranches}${formData_English.otherBranches === 'Y' ? `, ${formData_English.otherBranchesText}` : ''}\n`;
        output += `[RN Description]: ${formData_English.rnDescription}${formData_English.rnDescription === 'Y' ? `, ${formData_English.rnDescriptionText}` : ''}\n`;
        output += `<FSG/NV Update>: ${formData_English.fsgUpdate}\n`;
        if (formData_English.fsgUpdate === 'Y') {
          output += `<FSG TAG>: ${formData_English.fsgTag}\n`;
          output += `<FSG SW>: ${formData_English.fsgSW}\n`;
          output += `<FSG RF>: ${formData_English.fsgRF}\n`;
          output += `<FSG DATE>: ${formData_English.fsgDate}\n`;
        }
        output += `\n<<< Test Notes >>>\n`;
        output += `<SW-Test>: ${formData_English.softwareTest}${formData_English.softwareTestText ? `, ${formData_English.softwareTestText}` : ''}\n`;
        output += `<Stress Test>: ${formData_English.stressTest}${formData_English.stressTestText ? `, ${formData_English.stressTestText}` : ''}\n`;
        output += `<HW-Test>: ${formData_English.hardwareTest}${formData_English.hardwareTestText ? `, ${formData_English.hardwareTestText}` : ''}\n`;
        output += `<Addition or Modification of AT Commands in AP>: ${formData_English.apAtCommand}\n`;
        return output;
      };

      useEffect(() => {
        setOutputText(generateOutput());
      }, [formData]);

      useEffect(() => {
        setOutputText_English(generateOutput_English());
      }, [formData_English]);

        
      const [language, setLanguage] = useState("en"); // 'zh' or 'en'
        
      const toggledLanguage = () => {
        setLanguage((prev) => (prev === "en" ? "zh" : "en"));
      };
      const [translatedText, setTranslatedText] = useState("");
      const [inputLang, setInputLang] = useState("en"); // User selects input language

    const handleChangeT = (e) => {
      const { name, type, checked, value } = e.target;

      if (inputLang === "zh") {
        setFormData((prev) => ({
          ...prev,
          [name]: value,
        }));
      } else {
        setFormData_English((prev) => ({
          ...prev,
          [name] : value,
        }));
      }
    if (type === "checkbox"){
      setFormData((prev) => ({
          ...prev,
          [name]: checked ? "Y":"N",
        }));
        setFormData_English((prev) => ({
          ...prev,
          [name]: checked ? "Y":"N",
        }));
    }
    if(name === "commit_path_info" || name === "emailPrefix" || type === "radio" ||name === "emailString" || name === "projectname"){
      setFormData((prev) => ({
          ...prev,
          [name]: value,
        }));
        setFormData_English((prev) => ({
          ...prev,
          [name]: value,
        }));
    }
    };

    const handleLanguageChange = (e) => {
      setInputLang(e.target.value);
      setTranslatedText(""); // reset translation when switching language
    };

    const handleTranslateT = async (fieldName, originalText) => {
    const sourceLang = inputLang;
    const targetLang = inputLang === "zh" ? "en" : "zh";

    try {
      const containsChinese = /[\u4e00-\u9fa5]/.test(originalText);
      const containsEnglish = /[a-zA-Z]/.test(originalText);
      let translated;

      if ((inputLang === "zh" && containsChinese) || (inputLang === "en" && containsEnglish)) {
        const res = await fetch(
          `https://api.mymemory.translated.net/get?q=${encodeURIComponent(originalText)}&langpair=${inputLang}|${targetLang}`
        );
        const data = await res.json();
        translated = data.responseData.translatedText;
      } else {
        // If input doesn't contain Chinese, skip translation
        translated = originalText;
      }

      setTranslatedText(translated);

      if (targetLang === "zh") {
        setFormData((prev) => ({ ...prev, [fieldName]: translated }));
      } else {
        setFormData_English((prev) => ({ ...prev, [fieldName]: translated }));
      }
    } catch (error) {
      console.error("Translation failed:", error);
      translated = originalText
      setTranslatedText(originalText);
    }
  };
  const handleTranslateRisk = async (name, originalText) => {
  const sourceText = inputLang === "en" ? formData[name] : formData_English[name];
  if (!originalText) return;
  const linesT = sourceText.split("\n");
  const lines = originalText.split("\n");
  const targetLang = inputLang === "zh" ? "en" : "zh";
  let translatedLines = [];

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const lineT = linesT[i]; 
    const [prefixT, ...restT] = lineT.split(":");
    const [prefix, ...rest] = line.split(":");
    const valueToTranslate = rest.join(":").trim();

    if (!valueToTranslate) {
      translatedLines.push(lineT); // fallback to original line
      continue;
    }

    try {
      const containsChinese = /[\u4e00-\u9fa5]/.test(valueToTranslate);
      const containsEnglish = /[a-zA-Z]/.test(valueToTranslate);
      let translated_T = valueToTranslate;

      if ((inputLang === "zh" && containsChinese) || (inputLang === "en" && containsEnglish)) {
        const res = await fetch(
          `https://api.mymemory.translated.net/get?q=${encodeURIComponent(valueToTranslate)}&langpair=${inputLang}|${targetLang}`
        );
        const data = await res.json();
        translated_T = data.responseData.translatedText;
      }

      translatedLines[i] = `${prefixT}: ${translated_T}`;
    } catch (error) {
      console.error("Translation failed for line:", line, error);
      translatedLines[i] = lineT; // fallback if error
    }
  }

  const finalTranslatedText = translatedLines.join("\n");

  if (inputLang === "en") {
    setFormData((prev) => ({ ...prev, [name]: finalTranslatedText }));
  } else {
    setFormData_English((prev) => ({ ...prev, [name]: finalTranslatedText }));
  }
};
const handleFunctionChange = (e) => {
        const { value, checked } = e.target;
        setFormData(prevFormData => {
          const { affectedFunction } = prevFormData;
          let newFunctions;
          if (checked) {
            newFunctions = [...affectedFunction, value];
          } else {
            newFunctions = affectedFunction.filter(item => item !== value);
          }
          return { ...prevFormData, affectedFunction: newFunctions };
        });
        setFormData_English(prevFormData => {
          const { affectedFunction } = prevFormData;
          let newFunctions;
          if (checked) {
            newFunctions = [...affectedFunction, value];
          } else {
            newFunctions = affectedFunction.filter(item => item !== value);
          }
          return { ...prevFormData, affectedFunction: newFunctions };
        });
      };

const groupedItems = {
  "A":["ADC","AEP (lwm2m)","Alarm","alipay",inputLang === "zh" ? "APN自适应" : "APN Auto-Adaptation","AudioPlay","AudioRecord","AutoBaud","auotapn"],
  "B":[inputLang === "zh" ? "白名单" : "白名单 //Whitelist","BOOT","BT"],
  "C":["Call Quality&Volume","Camera","CellLocator","Charge","CMUX","Coap","Coaps","CSD"],
  "D":["Datacall","DataService","DFOTA","DIAG",inputLang === "zh" ? "电信自注册" : "电信自注册 //Telecom Self-Registration","DTLS","DM_CMCC","DM-Verity","DNS","Device Info","DSDS","DTMF","Dual UART",inputLang === "zh" ? "多网卡" : "多网卡 //Multi-SIM"],
  "E":["ECM","eDRX","EMMC","EINT","eSIM","ethernet"],
  "F":["Factory ATC","FILE","FOTA","FTP","FTPS","FullFOTA"],
  "G":["General","GNSS","GPIO","GW_Netlight"],
  "H":["HTTP","HTTPS","http2.0","HTTP OTA"],
  "I":["IMS","IPC low power","I2C"],
  "J":["Jamming","Jamming Detection"],
  "K":[inputLang === "zh" ? "开关机" : "开关机 //Power On/Off"],
  "L":["LCD",inputLang === "zh" ? "联通雁飞（mqtt, lwm2m）" : "联通雁飞 (MQTT, LwM2M) //Unicom Yanfei",inputLang === "zh" ? "联通自注册" : "联通自注册 //Unicom Self-Registration","Limited_Network",inputLang === "zh" ? "流量统计" : "流量统计 //Data Usage Statistics","Low Power","LwM2M","L2TP"],
  "M":[inputLang === "zh" ? "蚂蚁链" : "蚂蚁链 //AntChain","Matrix Key","MMS","MiniFOTA","MQTT","MQTT 5.0"],
  "N":["NAT","NCM","Netlight","Network","NITZ","NITZ&QNTP","NV"],
  "O":["OOS","OceanConnect","oneNet (lwm2m)",inputLang === "zh" ? "OneNET（只有运营商定制版本包含）" : "OneNET（只有运营商定制版本包含） //only operator-customized versions","OOM"],
  "P":["PCIE","PHB","PING","PPP","Pre_checklist","Pretest_checklist_ASR","ProductiveATCheck","ProductiveTest","PSM","PWM"],
  "Q":["QMI","Quec Locator","QuecFOTA","QuecLocator","QuecThing","QUECTHING","QuecThing OTA"],
  "R":["RF","RFTESTPWR","RNDIS","RTC"],
  "S":[inputLang === "zh" ? "扫码" : "扫码 //QR Code Scanning","SD","sd","SELinux","SecureBoot","SecurityTest","SFTP","SIM","SIM Detection","SIMCARD","SIMCardCompatibility","Slic","SMS","SMTP","SMTPS","SNMP","Sockets","SPI","SSL","status light","STK"],
  "T":["TCP SSL","TCP/UDP","TCPIP","TCP SSL",inputLang === "zh" ? "腾讯云" : "腾讯云 //Tencent Cloud","Timer","Triple UART","Trustzone","TTS"],
  "U":["UAC","UART","UFS","UpgradePowerONOFF","URC","URC&RI","URC&RI&Apready","USB","usb mass storage","USB Suspend","USB TR灯","USIM","USSD"],
  "V":["Version_Check","VIRT AT","Voice Call","VoLTE","vsim"],
  "W":["WeakSignal","websocket(s)","WIFI","WIFI Scan"],
  "X":["XLAT"],
  "Y":[inputLang === "zh" ? "异常基站检测" : "异常基站检测 //Abnormal Base Station Detection"],
  "Z":[inputLang === "zh" ? "自适应波特率" : "自适应波特率 //Adaptive Baud Rate"]
};

const scrollToLetter = (letter) => {
  const container = document.getElementById("scroll-container");
  const target = document.getElementById(`section-${letter}`);
  if (container && target) {
    container.scrollTo({
      top: target.offsetTop - 40, // offset for sticky nav
      behavior: "smooth",
    });
  }
};

const toggleItem = (item) => {
  setSelectedItems(prev =>
    prev.includes(item) ? prev.filter(i => i !== item) : [...prev, item]
  );
};
          
      return (
        <div className="container mx-auto p-4 max-w-9xl">
          <h1 className="text-3xl  font-bold mb-4">Commit Description Generator (v0.7)</h1>
          <div className="space-y-4">
          <button
          type="button"
          onClick={() =>
            setInputLang(prev => (prev === 'en' ? 'zh' : 'en'))
          }
          className="px-4 py-2 rounded bg-blue-500 text-white hover:bg-blue-600 transition"
          >
          {inputLang === 'zh' ? 'Translate to English' : '翻译成中文'}
          </button>
          <div>
            <label className="block text-sm font-medium mb-1">
              {inputLang === "zh"
                ? "提交P4生成的路径前缀"
                : "Path Prefix from P4 Commit"}
            </label>
            <input
              type="text"
              name="commit_path_info"
              value={inputLang === "zh"
                ? formData.commit_path_info || ""
                : formData_English.commit_path_info || ""}
              onChange={handleChangeT}
              className="block w-full border rounded p-2"
              placeholder={
                inputLang === "zh"
                  ? "如: <EIGEN><R05><PLAT><10.66.90.122>"
                  : "e.g. <EIGEN><R05><PLAT><10.66.90.122>"
              }
            />
          </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "邮箱前缀"
                  : "Email Prefix"}</label>
              <input
                type="text"
                name="emailPrefix"
                value={inputLang === "zh"
            ? formData.emailPrefix || ""
            : formData_English.emailPrefix || ""}
                onChange={handleChangeT}
                className="mt-1 block w-full border rounded p-2"
                placeholder={
                  inputLang === "zh"
                    ? "请输入邮箱前缀全称"
                    : "Please enter full email prefix"
                }
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">
                {inputLang === "zh"
                  ? "邮箱后的字符串"
                  : "String after the email address"}
              </label>
              <input
                type="text"
                name="emailString"
                value={inputLang === "zh"
                  ? formData.emailString || ""
                  : formData_English.emailString || ""}
                onChange={handleChangeT}
                className="block w-full border rounded p-2"
                placeholder={
                  inputLang === "zh"
                    ? "请输入邮箱后的字符串"
                    : "Please enter the string after the email address"
                }
              />
            </div>
            <div>
              <label className="block text-sm font-medium">integrate from</label>
              <input
                type="checkbox"
                name="integrate_from_flag"
                checked={formData.integrate_from_flag === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
              {formData.integrate_from_flag === 'Y' && (
                <textarea
                  name="integrate_from_id"
                            value={inputLang === "zh"
            ? formData.integrate_from_id || ""
            : formData_English.integrate_from_id || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                  onChange={handleChangeT}
                  className="mt-1 block w-full border rounded p-2 h-14 resize-none overflow-x-auto whitespace-nowrap"
                style={{ 
                  overflowY: 'hidden',
                  whiteSpace: 'nowrap',
                  resize: 'none'
                }}

                placeholder={inputLang === "zh"
                  ? "请输入对应integrate from的P4 ID或git commit ID"
                  : "Please enter the corresponding 'integrate from' P4 ID or Git commit ID."}
                />
              )}
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "修改点简述"
                  : "Modification Summary"}</label>
              <input
                type="text"
                name="changeDescription"
                          value={inputLang === "zh"
            ? formData.changeDescription || ""
            : formData_English.changeDescription || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                onChange={handleChangeT}
                className="mt-1 block w-full border rounded p-2"
                placeholder={inputLang === "zh"
                  ? "请输入修改点简述"
                  : "Please enter a brief description of modification"}
              />
            </div>
            <div>
              <label className="block text-sm font-medium">
                {inputLang === "zh" ? "修改分类" : "Change Type"}
              </label>
              <select
                name="changeCategory"
                value={formData.changeCategory}
                onChange={(e) => {
                  const selectedValue = e.target.value;
                  const optionsMap = {
                    "新增需求": "new requirements",
                    "客户缺陷修改": "customer bug fix",
                    "内部缺陷修改": "inner bug fix",
                  };

                  // Update both Mandarin and English states
                  setFormData((prev) => ({
                    ...prev,
                    changeCategory: selectedValue,
                  }));
                  setFormData_English((prev) => ({
                    ...prev,
                    changeCategory: optionsMap[selectedValue] || "",
                  }));
                }}
                className="mt-1 block w-full border rounded p-2"
              >
                <option value="新增需求">
                  {inputLang === "zh" ? "新增需求" : "new requirements"}
                </option>
                <option value="客户缺陷修改">
                  {inputLang === "zh" ? "客户缺陷修改" : "customer bug fix"}
                </option>
                <option value="内部缺陷修改">
                  {inputLang === "zh" ? "内部缺陷修改" : "inner bug fix"}
                </option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "根本原因"
                  : "Root Cause"}</label>
              <textarea
                name="rootCause"
                          value={inputLang === "zh"
            ? formData.rootCause || ""
            : formData_English.rootCause || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                onChange={handleChangeT}
                className="mt-1 block w-full border rounded p-2"
                placeholder={inputLang === "zh"
                  ? "请输入根本原因"
                  : "Describe the root cause of the problem"}
              />
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "解决方案"
                  : "Solution"}</label>
              <textarea
                name="solution"
                          value={inputLang === "zh"
            ? formData.solution || ""
            : formData_English.solution || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                onChange={handleChangeT}
                className="mt-1 block w-full border rounded p-2"
                placeholder={inputLang === "zh"
                  ? "请输入解决方案"
                  : "Describe the solution idea"}
              />
            </div>
            <div>
              <label className="block text-sm font-medium">Jira ID</label>
              <input
                type="checkbox"
                name="jiraID_flag"
                checked={formData.jiraID_flag === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
              {formData.jiraID_flag === 'Y' && (
                <textarea
                  name="jiraID"
                            value={inputLang === "zh"
            ? formData.jiraID || ""
            : formData_English.jiraID || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                  onChange={handleChangeT}
                  className="mt-1 block w-full border rounded p-2 h-14 resize-none overflow-x-auto whitespace-nowrap"
                style={{ 
                  overflowY: 'hidden',
                  whiteSpace: 'nowrap',
                  resize: 'none'
                }}

                placeholder={inputLang === "zh"
                  ? "若涉及填写关联的Jira ID，若多个以英文逗号分隔，若提交修改点已绑定Jira ID，此处填N"
                  : "If Jira ID is not involved, fill in N. If a Jira ID is involved, fill in the specific Jira ID number. When multiple Jira IDs are involved, the Jira ID numbers need to be separated by English commas."}
                />
              )}
            </div>
            <div>
              <label className="block text-sm font-medium">CVE ID</label>
              <input
                type="checkbox"
                name="cveID_flag"
                checked={formData.cveID_flag === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
              {formData.cveID_flag === 'Y' && (
                <textarea
                  name="cveID"
                            value={inputLang === "zh"
            ? formData.cveID || ""
            : formData_English.cveID || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                  onChange={handleChangeT}
                  className="mt-1 block w-full border rounded p-2 h-14 resize-none overflow-x-auto whitespace-nowrap"
                style={{ 
                  overflowY: 'hidden',
                  whiteSpace: 'nowrap',
                  resize: 'none'
                }}

                placeholder={inputLang === "zh"
                  ? "请输入CVE ID，不涉及填N"
                  : "If CVE vulnerabilities fixing is involved, fill in the CVE ID; otherwise, fill in N."}
                />
              )}
            </div>
            <div className = "space-y-4">
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "影响功能名称"
                  : "Affected Function Name"}</label>
                <div className="flex items-center space-x-20 mt-1">
                  <label className="inline-flex items-center">
                    <input
                      type="checkbox"
                      value="General"
                      checked={formData.affectedFunction.includes('General')}
                      onChange={handleFunctionChange}
                      className="form-checkbox h-5 w-5 text-blue-600 shrink-0"
                    />
                    <span className="ml-2 text-sm">General</span>
                  </label>
                  <label className="inline-flex items-center">
                    <input
                      type="checkbox"
                      value="other"
                      checked={formData.affectedFunction.includes('other')}
                      onChange={handleFunctionChange}
                      className="form-checkbox h-5 w-5 text-blue-600 shrink-0"
                    />
                    <span className="ml-2 text-sm">{inputLang === "zh"
                    ? "other 当以下功能列表没有时生成后需手动替换实际内容,如果为多个功能项使用英语“,”做分割"
                    : "other, If listed features missing, replace with actual content manually, use ',' (English) to separate multiple items."}</span>
                  </label>
                </div>
            
                <div
                  id="scroll-container"
                  style={{
                    position: "relative",
                    height: "600px",
                    overflowY: "auto",
                    border: "1px solid #ccc",
                  }}
                >
                {/* Top Alphabet Navigation */}
                <div
                  style={{
                    position: "sticky",
                    top: 0,
                    background: "white",
                    zIndex: 2,
                    padding: "5px",
                    borderBottom: "1px solid #ddd",
                    display: "flex",
                    gap: "5px",
                    flexWrap: "wrap",
                  }}
                >
                  {Object.keys(groupedItems).map((letter) => (
                    <button
                      key={letter}
                      onClick={() => scrollToLetter(letter)}
                      style={{
                        padding: "4px 6px",
                        fontSize: "14px",
                        cursor: "pointer",
                      }}
                    >
                      {letter}
                    </button>
                  ))}
                </div>
                {/* Scrollable List */}
                  {Object.keys(groupedItems).map((letter,index) => (
                    <div key={letter} id={`section-${letter}`}>
                      <div style={{
                        display: 'grid',
                        gridTemplateColumns: 'repeat(6, 1fr)',
                        gap: '15px',
                        padding: '5px',
                        backgroundColor: index % 2 === 0 ? '#eee' : 'white'
                      }}> 
                        {groupedItems[letter].map(item => (
                          <div  className="inline-flex items-center" key={item}>
                            <input
                              type="checkbox"
                              value={item.split(" //")[0]}
                              checked={formData.affectedFunction.includes(item.split(" //")[0])}
                              onChange={handleFunctionChange}
                              className="form-checkbox h-5 w-5 text-blue-600 shrink-0"
                            />
                            <span className="ml-2 text-sm">{item}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "适用项目"
                  : "Applicable Project"}</label>
              <select
                name="applicableProject"
                value={formData.applicableProject}
                onChange={(e) => {
                  const selectedValue = e.target.value;
                  const optionsMap = {
                    "分支测试": "branch test",
                    "其他": "others",
                  };

                  // Update both Mandarin and English states
                  setFormData((prev) => ({
                    ...prev,
                    applicableProject: selectedValue,
                  }));
                  setFormData_English((prev) => ({
                    ...prev,
                    applicableProject: optionsMap[selectedValue] || "",
                  }));
                }}
                className="mt-1 block w-full border rounded p-2"
              >
              <option value="分支测试">{inputLang === "zh"
                  ? "分支测试"
                  : "branch test"}</option>
              <option value="其他">{inputLang === "zh"
                  ? "其他" 
                  : "others"}
              </option>
            </select>
            {formData_English.applicableProject === "others" && 
              <input
                type = "text"
                name="projectname"
                value={formData.projectname || ""}
                onChange={handleChangeT}
                className="block w-full border rounded p-2"
                placeholder={
                  inputLang === "zh"
                    ? "芯片平台+具体项目名"
                    : "chip platform + specific name of the project"
                }
              />
            }
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "影响项目类型"
                  : "Affected Project Type"}</label>
              <select
                name="projectType"
                value={formData.projectType}
                onChange={(e) => {
                  const selectedValue = e.target.value;
                  const optionsMap = {
                    "标准项目": "Standard Project",
                    "Open项目": "Open Project",
                    "标准项目": "Open + Standard Project",
                  };
                  // Update both Mandarin and English states
                  setFormData((prev) => ({
                    ...prev,
                    projectType: selectedValue,
                  }));
                  setFormData_English((prev) => ({
                    ...prev,
                    projectType: optionsMap[selectedValue] || "",
                  }));
                }}
                className="mt-1 block w-full border rounded p-2"
              >
              <option value="标准项目">{inputLang === "zh"
                  ? "标准项目"
                  : "Standard Project"}</option>
                <option value="Open项目">{inputLang === "zh"
                  ? "Open项目"
                  : "Open Project"}</option>
                <option value="Open+标准项目">{inputLang === "zh"
                  ? "Open+标准项目"
                  : "Open + Standard Project"}</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "风险等级"
                  : "Risk level"}</label>
              <textarea
                name="riskLevel"
                value={inputLang === "zh"
                  ? formData.riskLevel
                  : formData_English.riskLevel}
                  onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateRisk(e.target.name, value); // auto-translate on blur
                }
              }}
                onChange={handleChangeT}
                className="mt-1 block w-full border rounded p-2 h-28"
                placeholder={inputLang === "zh"
                  ? "请输入风险等级（十部必填）"
                  : "Software Department X must fill in the risk level and other departments are not required ."}
              />
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "关联其它修改点"
                  : "Associated Changes"}</label>
              <input
                type="checkbox"
                name="relatedChanges_flag"
                checked={formData.relatedChanges_flag === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
              {formData.relatedChanges_flag === 'Y' && (
                <textarea
                  name="relatedChanges"
                  value={inputLang === "zh"
            ? formData.relatedChanges || ""
            : formData_English.relatedChanges || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                  onChange={handleChangeT}
                  className="mt-1 block w-full border rounded p-2 h-14 resize-none overflow-x-auto whitespace-nowrap"
                style={{ 
                  overflowY: 'hidden',
                  whiteSpace: 'nowrap',
                  resize: 'none'
                }}

                placeholder={inputLang === "zh"
                  ? "如有填写对应P4 ID or git commit ID，以英文逗号分隔,若不涉及填写N"
                  : "List the associated changelists if any. And multiple changelists need to be separated by English commas;otherwise, fill in N."}
                />
              )}
            </div>
            <h2 className="text-xl font-semibold mt-6">{inputLang === "zh"
                  ? "研发自检"
                  : "Self-check by Developers"}</h2>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "ATC 文档名称"
                  : "ATC Document Name"}</label>
              <input
                type="checkbox"
                name="atcDoc_flag"
                checked={formData.atcDoc_flag === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
              {formData.atcDoc_flag === 'Y' && (
                <textarea
                  name="atcDoc"
                  value={inputLang === "zh"
            ? formData.atcDoc || ""
            : formData_English.atcDoc || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                  onChange={handleChangeT}
                  className="mt-1 block w-full border rounded p-2 h-14 resize-none overflow-x-auto whitespace-nowrap"
                style={{ 
                  overflowY: 'hidden',
                  whiteSpace: 'nowrap',
                  resize: 'none'
                }}

                  placeholder={inputLang === "zh"
                  ? "填写ATC文档名称及文档路径"
                  : "Enter the ATC document name and file path."}
                />
              )}
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否使用运营商DM协议"
                  : "Operator DM protocol"}</label>
              <input
                type="checkbox"
                name="dmProtocol"
                checked={formData.dmProtocol === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否使用第三方服务器"
                  : "Server of Third-Party"}</label>
              <input
                type="checkbox"
                name="thirdPartyServer"
                checked={formData.thirdPartyServer === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否使用第三方软件"
                  : "Sw of Third-Party"}</label>
              <input
                type="checkbox"
                name="thirdPartySoftware"
                checked={formData.thirdPartySoftware === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否为音频默认参数"
                  : "Audio Default Parameters"}</label>
              <input
                type="checkbox"
                name="audioDefault"
                checked={formData.audioDefault === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否修改配置文件"
                  : "Conf files Modification: such as rawdata Partition"}</label>
              <input
                type="checkbox"
                name="configChange"
                checked={formData.configChange === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否修改MBN"
                  : "MBN Modifications"}</label>
              <select
                name="mbnChange"
                value={formData.mbnChange}
                onChange={(e) => {
                  const selectedValue = e.target.value;
                  const optionsMap = {
                    "N": "N",
                    "Y,无需更新mbn数据库": "Y. Do not need to update MBN data library",
                    "Y,已更新mbn数据库": "Y. MBN data library is updated",
                  };
                  // Update both Mandarin and English states
                  setFormData((prev) => ({
                    ...prev,
                    mbnChange: selectedValue,
                  }));
                  setFormData_English((prev) => ({
                    ...prev,
                    mbnChange: optionsMap[selectedValue] || "",
                  }));
                }}
                className="mt-1 block w-full border rounded p-2"
              >
              <option value="N">N</option>
                <option value="Y,无需更新mbn数据库">{inputLang === "zh"
                  ? "Y,无需更新mbn数据库"
                  : "Y. Do not need to update MBN data library"}</option>
                <option value="Y,已更新mbn数据库">{inputLang === "zh"
                  ? "Y,已更新mbn数据库"
                  : "Y. MBN data library is updated"}</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否存在定时器非预期的唤醒和休眠锁未释放"
                  : "Whether the timer has an unexpected wake up and sleep lock that is not released"}</label>
              <input
                type="checkbox"
                name="timerIssue"
                checked={formData.timerIssue === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否存在参数结构变更影响前后版本的兼容性"
                  : "Check whether the parameter structure changes affect the compatibility between versions before and after"}</label>
              <input
                type="checkbox"
                name="paramCompatibility"
                checked={formData.paramCompatibility === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否存在NV/文件系统/存储介质的频繁擦写"
                  : "Frequent Erasing of NV/File System/Storage Media"}</label>
              <input
                type="checkbox"
                name="storageWear"
                checked={formData.storageWear === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否存在客户敏感信息泄漏"
                  : "Whether there is leakage of customer sensitive information"}</label>
              <input
                type="checkbox"
                name="sensitiveInfo"
                checked={formData.sensitiveInfo === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否存在重要参数还原失败系统不停重启或变砖"
                  : "Check whether important parameters fail to be restored. The system keeps restarting or becomes brick"}</label>
              <input
                type="checkbox"
                name="paramReset"
                checked={formData.paramReset === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "是否更新API文档"
                  : "Whether API document is updated"}</label>
              <input
                type="checkbox"
                name="apiDocUpdate"
                checked={formData.apiDocUpdate === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "其他需要合入的分支"
                  : "Other Branches to be Merged"}</label>
              <input
                type="checkbox"
                name="otherBranches"
                checked={formData.otherBranches === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
              {formData.otherBranches === 'Y' && (
                <input
                  type="text"
                  name="otherBranchesText"
                            value={inputLang === "zh"
            ? formData.otherBranchesText || ""
            : formData_English.otherBranchesText || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                  onChange={handleChangeT}
                  className="mt-1 block w-full border rounded p-2"
                  placeholder={inputLang === "zh"
                  ? "请输入需要合入的分支"
                  : "Fill in the branches that need to be merged"}
                />
              )}
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "RN描述"
                  : "RN description"}</label>
              <input
                type="checkbox"
                name="rnDescription"
                checked={formData.rnDescription === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
              {formData.rnDescription === 'Y' && (
                <textarea
                  name="rnDescriptionText"
                            value={inputLang === "zh"
            ? formData.rnDescriptionText || ""
            : formData_English.rnDescriptionText || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                  onChange={handleChangeT}
                  className="mt-1 block w-full border rounded p-2"
                  placeholder={inputLang === "zh"
                  ? "请输入RN描述"
                  : "Fill in RN description"}
                />
              )}
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "FSG/NV更新"
                  : "FSG/NV Update"}</label>
              <input
                type="checkbox"
                name="fsgUpdate"
                checked={formData.fsgUpdate === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
              {formData.fsgUpdate === 'Y' && (
                <div className="space-y-2 mt-2">
                  <input
                    type="text"
                    name="fsgTag"
                              value={inputLang === "zh"
            ? formData.fsgTag || ""
            : formData_English.fsgTag || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                    onChange={handleChangeT}
                    className="block w-full border rounded p-2"
                    placeholder={inputLang === "zh"
                  ? "请输入FSG TAG"
                  : "Fill in FSG TAG"}
                  />
                  <input
                    type="text"
                    name="fsgSW"
                              value={inputLang === "zh"
            ? formData.fsgSW || ""
            : formData_English.fsgSW || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                    onChange={handleChangeT}
                    className="block w-full border rounded p-2"
                    placeholder={inputLang === "zh"
                  ? "请输入FSG SW"
                  : "Fill in FSG SW"}
                  />
                  <input
                    type="text"
                    name="fsgRF"
                              value={inputLang === "zh"
            ? formData.fsgRF || ""
            : formData_English.fsgRF || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                    onChange={handleChangeT}
                    className="block w-full border rounded p-2"
                    placeholder={inputLang === "zh"
                  ? "请输入FSG RF"
                  : "Fill in FSG RF"}
                  />
                  <input
                    type="text"
                    name="fsgDate"
                              value={inputLang === "zh"
            ? formData.fsgDate || ""
            : formData_English.fsgDate || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                    onChange={handleChangeT}
                    className="block w-full border rounded p-2"
                    placeholder={inputLang === "zh"
                  ? "请输入FSG DATE"
                  : "Fill in FSG DATE"}
                  />
                </div>
              )}
            </div>
            <h2 className="text-xl font-semibold mt-6">Test Notes</h2>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "软件测试"
                  : "SW-Test"}</label>
              <div className="flex items-center space-x-4 mt-1">
                 <label><input type="radio" name="softwareTest" value="Y" checked={inputLang === "zh" ? formData.softwareTest === 'Y' : formData_English.softwareTest === 'Y'} onChange={handleChangeT} className="mr-1"/> Y</label>
                 <label><input type="radio" name="softwareTest" value="N" checked={inputLang === "zh" ? formData.softwareTest === 'N' : formData_English.softwareTest === 'N'} onChange={handleChangeT} className="mr-1"/> N</label>
              </div>
              <textarea
                name="softwareTestText"
                          value={inputLang === "zh"
            ? formData.softwareTestText || ""
            : formData_English.softwareTestText || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                onChange={handleChangeT}
                className="mt-1 block w-full border rounded p-2"
                placeholder={inputLang === "zh"
                  ? "请输入具体原因"
                  : "Please enter specific reason"}
              />
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "压力测试"
                  : "Stress Test"}</label>
              <div className="flex items-center space-x-4 mt-1">
                 <label><input type="radio" name="stressTest" value="Y" checked={inputLang === "zh" ? formData.stressTest === 'Y' : formData_English.stressTest === 'Y'} onChange={handleChangeT} className="mr-1"/> Y</label>
                 <label><input type="radio" name="stressTest" value="N" checked={inputLang === "zh" ? formData.stressTest === 'N' : formData_English.stressTest === 'N'} onChange={handleChangeT} className="mr-1"/> N</label>
              </div>
              <textarea
                name="stressTestText"
                          value={inputLang === "zh"
            ? formData.stressTestText || ""
            : formData_English.stressTestText || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                onChange={handleChangeT}
                className="mt-1 block w-full border rounded p-2"
                placeholder={inputLang === "zh"
                  ? "请输入具体原因"
                  : "Please enter specific reason"}
              />
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "硬件测试"
                  : "HW-Test"}</label>
              <div className="flex items-center space-x-4 mt-1">
                 <label><input type="radio" name="hardwareTest" value="Y" checked={inputLang === "zh" ? formData.hardwareTest === 'Y' : formData_English.hardwareTest === 'Y'} onChange={handleChangeT} className="mr-1"/> Y</label>
                 <label><input type="radio" name="hardwareTest" value="N" checked={inputLang === "zh" ? formData.hardwareTest === 'N' : formData_English.hardwareTest === 'N'}  onChange={handleChangeT} className="mr-1"/> N</label>
              </div>
              <textarea
                name="hardwareTestText"
                valueT={inputLang === "zh"
            ? formData.hardwareTestText || ""
            : formData_English.hardwareTestText || ""}
            onBlur={(e) => {
                const value = e.target.value;
                if (value.trim() !== "") {
                  handleTranslateT(e.target.name, value); // auto-translate on blur
                }
              }}
                onChange={handleChangeT}
                className="mt-1 block w-full border rounded p-2"
                placeholder={inputLang === "zh"
                  ? "请输入具体原因"
                  : "Please enter specific reason"}
              />
            </div>
            <div>
              <label className="block text-sm font-medium">{inputLang === "zh"
                  ? "AP侧AT指令新增或修改"
                  : "Addition or Modification of AT Commands in AP"}
              </label>
              <input
                type="checkbox"
                name="apAtCommand"
                checked={formData.apAtCommand === 'Y'}
                onChange={handleChangeT}
                className="mt-1"
              /> Y
            </div>
            <div className="flex space-x-2">
              <button
                onClick={() => {
                  const combinedText = inputLang=== "zh" ? `${outputText}\n\n${outputText_English}`: `${outputText_English}\n\n${outputText}`;
                  navigator.clipboard.writeText(combinedText).then(() => alert(inputLang === "zh"
                  ? "已复制到剪贴板!"
                  : "Copied to clipboard"));
                }}
                className="mt-4 bg-blue-500 text-white p-2 rounded"
              >
                {inputLang === "zh"
                  ? "复制中英内容"
                  : "Copy English and Chinese content"}
              </button>
              <button
                onClick={() => {
                  navigator.clipboard.writeText(outputText).then(() => alert(inputLang === "zh"
                  ? "已复制到剪贴板!"
                  : "Copied to clipboard"));
                }}
                className="mt-4 bg-blue-500 text-white p-2 rounded"
              >
                {inputLang === "zh"
                  ? "复制中文内容"
                  : "Copy Chinese Content"}
              </button>
              <button
                onClick={() => {
                  navigator.clipboard.writeText(outputText_English).then(() => alert(inputLang === "zh"
                  ? "已复制到剪贴板!"
                  : "Copied to clipboard"));
                }}
                className="mt-4 bg-blue-500 text-white p-2 rounded"
              >
                {inputLang === "zh"
                  ? "复制英文内容"
                  : "Copy English Content"}
              </button>
              <button
              onClick={handleTranslateT}
                className="mt-4 bg-green-500 text-white p-2 rounded"
              >
                {inputLang === "zh"
                  ? "中英翻译"
                  : "Chinese-English Translation"}
              </button>
            </div>
            <div className="h-screen p-4">
              <div className="flex gap-4 h-full">
                <div className="flex-1 flex flex-col">
                  <label className="text-sm font-medium">输出预览</label>
                  <textarea
                    readOnly
                    value={outputText}
                    className="mt-1 flex-1 block w-full border rounded p-2 resize-none"
                  />
                </div>

                <div className="flex-1 flex flex-col">
                  <label className="text-sm font-medium">Output Preview</label>
                  <textarea
                    readOnly
                    value={outputText_English}
                    className="mt-1 flex-1 block w-full border rounded p-2 resize-none"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      );
    };

    ReactDOM.render(<CommitForm />, document.getElementById('root'));
  </script>
</body>

</html>